package com.chen.demo.config;

import com.chen.common.exception.CodeThrow;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @author ex_chenzy59
 * @since 2025/6/3
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(authorize-> authorize.requestMatchers("hello").permitAll())
                .formLogin(formLogin-> formLogin
    //                    .loginPage("/login.html")/*登录页面*/
                        .loginProcessingUrl("/login")/*登录接口*/
                        .failureHandler((_, resp, e) -> {
                            resp.setContentType("application/json;charset=utf-8");
                            var codeThrow= switch (e) {
                                case BadCredentialsException _ -> CodeThrow.Login_Bad_Credentials;
                                case AccountExpiredException _ -> CodeThrow.Login_Account_Expired;
                                case CredentialsExpiredException _ -> CodeThrow.Login_Credentials_Expired;
                                case DisabledException _ -> CodeThrow.Login_Disabled;
                                case LockedException _ -> CodeThrow.Login_Locked;
                                default -> CodeThrow.Login_Fail;
                            };
                            var text= """
                                    "code" : %d,"message": "%s","data":null
                                    """.formatted(codeThrow.code,codeThrow.msg);
                            resp.getWriter().write(text);
                        })
                        .permitAll())
                .rememberMe(Customizer.withDefaults())
        ;
        return http.build();
    }
}
